package com.qc.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author buhao
 * @version WsServerEndpoint.java, v 0.1 2019-10-18 16:06 buhao
 */
@ServerEndpoint("/myWs")
@Component
public class WsServerEndpoint {

    // 存储所有连接的客户端会话
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());

    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("连接成功，当前连接数: " + sessions.size());
    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("连接关闭，当前连接数: " + sessions.size());
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public void onMsg(String text) throws IOException {
        // 广播消息给所有连接的客户端
        System.out.println(text);
        for (Session session : sessions) {
            System.out.println(session);
            if (session.isOpen()) {
                session.getBasicRemote().sendText(text);
            }
        }
    }

    /**
     * 发生错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("发生错误: " + error.getMessage());
        error.printStackTrace();
    }
}